﻿
using Core;
using System.Collections.Generic;
using UnityEngine;

public class RandomSkillComponent : Entity, IAwake
{
    private const int weightMax = 1000;
    private readonly Dictionary<int, int> weightDict = new Dictionary<int, int>();
    private List<int> list = new List<int>();
    void IAwake.Awake()
    {
        var configs = World.GetComponent<ConfigComponent>().GetAllConifg<RandomSkillCoinfig>();

        List<int> roots = new List<int>();
        foreach (var config in configs)
        {
            if (config.parent == 0)
            {
                roots.Add(config.id);
            }
            weightDict[config.id] = 0;
        }
        var weight = Mathf.RoundToInt((float)weightMax / roots.Count);
        foreach (var id in roots)
        {
            weightDict[id] = weight;
        }
        UpdateList();
    }

    public void SelectSkill(int id)
    {
        var config = World.GetComponent<ConfigComponent>().GetConfig<RandomSkillCoinfig>(id);
        if (config == null)
            return;

        if (config.parent == 0)
        {
            if(config.childs != null)
            {
                var totalWeight = weightDict[config.id];
                var weight = Mathf.RoundToInt((float)totalWeight / config.childs.Count);
                foreach (var childConfig in config.childs)
                {
                    weightDict[childConfig.id] = weight;
                }
                UpdateList();
            }
            weightDict.Remove(config.id);
        }

        SkillCastArgs args = new SkillCastArgs();
        args.skillId = config.skillId;
        var unit = Player.Instance.GetParent<Unit>();
        var skillComponent = unit.GetComponent<SkillComponent>();
        skillComponent.AddSkill(config.skillId);
        skillComponent.TryCastSkill(args);
    }

    public int RandomSkill()
    {
        if (list.Count == 0)
            return 0;
        int count = UnityEngine.Random.Range(0, weightMax);
        int weight = 0;
        for (int i = 0; i < list.Count; i++)
        {
            if (weightDict.TryGetValue(list[i], out var value))
            {
                weight += value;
            }
            if (count < weight)
            {
                return list[i];
            }
        }
        return list[list.Count - 1];
    }

    void UpdateList()
    {
        list.Clear();
        foreach (var item in weightDict)
        {
            if (item.Value != 0)
            {
                list.Add(item.Key);
            }
        }
    }
}